<?php


namespace SidToken\Utils;


use SidToken\Model\InviteUserModel;
use SidToken\Model\SidTransferLogModel;
use SidToken\Model\SidTrxErrModel;
use SidToken\Model\SidUserMinerModel;

class RewardUtil
{
    function snapshotUserMinerCount($uid)
    {
        $UserMinerModel = new SidUserMinerModel();
        $count = S("snapshotUserMinerCount_{$uid}");
        if (!$count) {
            $count = $UserMinerModel->where(['uid' => $uid, 'status' => $UserMinerModel::STATUS_ON])->count();
            if ($count == 0) {
                $count = -1;
            }
            S("snapshotUserMinerCount_{$uid}", $count, 21600);
        }
        return intval($count);
    }

    function rewardMining($uid, $minerName, $amount)
    {
        $InviteUserModel = new InviteUserModel();
        $level1Uid = $InviteUserModel->getInviteUid($uid, 1);
        $level2Uid = $InviteUserModel->getInviteUid($uid, 2);
        $level3Uid = $InviteUserModel->getInviteUid($uid, 3);

        $inviteUids = [$level1Uid, $level2Uid, $level3Uid];

        $rewardAmountArr = [];
        if ($level1Uid) {
            $level1Amount = $amount * 0.1;
            if ($level1Amount > 0) {
                $rewardAmountArr[] = $level1Amount;
            }
        }
        if ($level2Uid) {
            $level2Amount = $amount * 0.05;
            if ($level2Amount > 0) {
                $rewardAmountArr[] = $level2Amount;
            }
        }
        if ($level3Uid) {
            $level3Amount = $amount * 0.02;
            if ($level3Amount > 0) {
                $rewardAmountArr[] = $level3Amount;
            }
        }
        for ($i = 0; $i < 3; $i++) {
            $rewardAmount = $rewardAmountArr[$i];
            $inviteUid = $inviteUids[$i];
            if (!$rewardAmount || !$inviteUid) {
                break;
            }
            $level = $i + 1;
            $reason = "{$level}代好友（{$uid}）{$minerName}算力加成";
            $this->doRewardMining($inviteUid, $rewardAmount, $reason);
        }
        return true;
    }

    function doRewardMining($uid, $amount, $reason)
    {
        $MemberWallet = new MemberWalletUtil();
        $snapshotUserMinerCount = $this->snapshotUserMinerCount($uid);
        if ($snapshotUserMinerCount > 0) {//有矿机的用户才发放奖励
            $MemberWallet->changeSid($uid, 'inc', 'inner transfer', 'inner transfer', time() . mt_rand(1000, 9999), $amount, $reason);
        }

    }
}